
package com.eyedog.video.splash;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.eyedog.video.MainActivity;
import com.eyedog.video.R;
import com.eyedog.video.entity.ADVEntity;
import com.eyedog.video.entity.AdvVideoEntity;
import com.eyedog.video.entity.ApiEntity;
import com.eyedog.video.entity.CustomerEntity;
import com.eyedog.video.entity.ProfileEntity;
import com.eyedog.video.entity.SplashEntity;
import com.eyedog.video.http.HttpClient;
import com.eyedog.video.http.ICallback;
import com.eyedog.video.mine.ProfileInstance;
import com.eyedog.video.utils.DeviceUtil;
import com.eyedog.video.videolist.VideoModel;
import com.wallj.videolibrary.base.BaseVideoActivity;

import java.util.List;

public class SplashActivity extends BaseVideoActivity implements constract.IADView {
    private final String TAG = "SplashActivity";

    private ADVPresenter mPresenter;

    private SplashEntity mSplashEntity;

    private int mCurrentSecond = 0, mCurrentIndex = 0;

    private TextView mSecondTextView;

    private ImageView mIvSplash;

    private FrameLayout mSplashLayout;

    private final int PRELOAD_PAGES = 10;

    @Override
    protected void onContentCreated(ViewStub contentLayout) {
        contentLayout.setLayoutResource(R.layout.layout_splash);
        mSplashLayout = (FrameLayout) contentLayout.inflate();
        mSecondTextView = (TextView) findViewById(R.id.tv_second);
        mSecondTextView.setVisibility(View.GONE);
        mIvSplash = (ImageView) findViewById(R.id.iv_splash);
        mRootLayout.setBackgroundColor(getResources().getColor(R.color.black));
        mSplashLayout.setBackgroundColor(getResources().getColor(R.color.black));
        mPresenter = new ADVPresenter(this, new ADVModel());

        startLoading();
        VideoModel videoModel = new VideoModel();
        startPreloadVideo(videoModel);
    }

    int preloadTimes = 0;

    private void startPreloadVideo(final VideoModel videoModel) {
        if (preloadTimes < PRELOAD_PAGES) {
            if (!HttpClient.getInstance().hasApiRequested()) {
                HttpClient.getInstance().requestApi(new ICallback<ApiEntity>() {
                    @Override
                    public void onLoadSuccess(ApiEntity apiEntity) {
                        if (preloadTimes == 0 && ProfileInstance.getInstance().getProfileEntity() == null) {
                            String uniquecode = DeviceUtil.getUniquePsuedoID();
                            ProfileInstance.getInstance().setUniqueCode(uniquecode);
                            Log.i(TAG, "onLoadSuccess:" + uniquecode);
                            HttpClient.getInstance().requestProfile(uniquecode,
                                    new ICallback<ProfileEntity>() {
                                        @Override
                                        public void onLoadSuccess(ProfileEntity profileEntity) {
                                            Log.i(TAG, "onLoadSuccess profileEntity:");
                                            ProfileInstance.getInstance()
                                                    .setProfileEntity(profileEntity);
                                        }

                                        @Override
                                        public void onLoadFailed(String err) {
                                            Log.i(TAG, "onLoadFailed profileEntity:");
                                        }
                                    });
                            HttpClient.getInstance().requestCustomerEntity(new ICallback<List<CustomerEntity>>() {
                                @Override
                                public void onLoadSuccess(List<CustomerEntity> customerEntities) {
                                    ProfileInstance.getInstance().setCustomerEntities(customerEntities);
                                }

                                @Override
                                public void onLoadFailed(String err) {
                                }
                            });
                        }
                        preloadTimes++;
                        Log.i(TAG, "startPreloadVideo0: " + preloadTimes);
                        videoModel.loadRecommendVideoList(preloadTimes,
                                new ICallback<List<AdvVideoEntity>>() {
                                    @Override
                                    public void onLoadSuccess(
                                            List<AdvVideoEntity> advVideoEntities) {
                                        Log.i(TAG,
                                                "startPreloadVideo1: " + advVideoEntities.size());
                                        startPreloadVideo(videoModel);
                                    }

                                    @Override
                                    public void onLoadFailed(String err) {
                                        Log.i(TAG, "startPreloadVideo failed: " + preloadTimes);
                                    }
                                });
                    }

                    @Override
                    public void onLoadFailed(String err) {
                    }
                });
            } else {
                preloadTimes++;
                Log.i(TAG, "startPreloadVideo0: " + preloadTimes);
                videoModel.loadRecommendVideoList(preloadTimes,
                        new ICallback<List<AdvVideoEntity>>() {
                            @Override
                            public void onLoadSuccess(List<AdvVideoEntity> advVideoEntities) {
                                Log.i(TAG, "startPreloadVideo1: " + advVideoEntities.size());
                                startPreloadVideo(videoModel);
                            }

                            @Override
                            public void onLoadFailed(String err) {
                                Log.i(TAG, "startPreloadVideo failed: " + preloadTimes);
                            }
                        });
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            mPresenter.startSplash();
        }
    }

    private final int MSG_UI_ENTER_MAIN = 0x01;

    private final int MSG_UI_CHECK_SECOND = 0x02;

    private final int MSG_UI_REFRESH_ADV = 0x03;

    @Override
    protected void handleUIMessage(Message message) {
        super.handleUIMessage(message);
        switch (message.what) {
            case MSG_UI_REFRESH_ADV: {
                if (mSplashEntity != null && mSplashEntity.advEntities != null
                        && mSplashEntity.advEntities.size() > 0) {
                    if (mCurrentIndex < mSplashEntity.advEntities.size()) {
                        ADVEntity currentAdvEntity = mSplashEntity.advEntities.get(mCurrentIndex);
                        Log.i(TAG, "Glide:" + currentAdvEntity.img);
                        Glide.with(this).load(currentAdvEntity.img)
                                .placeholder(new ColorDrawable(Color.BLACK))
                                .into(new SimpleTarget<GlideDrawable>() {
                                    @Override
                                    public void onResourceReady(final GlideDrawable resource,
                                                                GlideAnimation<? super GlideDrawable> glideAnimation) {
                                        mIvSplash.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                mIvSplash.setImageDrawable(resource.getCurrent());
                                                stopLoading();
                                            }
                                        });
                                    }
                                });
                        sendEmptyUIMessageDelay(MSG_UI_REFRESH_ADV,
                                (mSplashEntity.duration / mSplashEntity.advEntities.size()));
                        mCurrentIndex++;
                    }
                }
            }
            break;
            case MSG_UI_CHECK_SECOND:
                if (mCurrentSecond <= 0) {
                    sendEmptyUIMessage(MSG_UI_ENTER_MAIN);
                } else {
//                    mSecondTextView.setVisibility(View.VISIBLE);
//                    mSecondTextView.setText(mCurrentSecond + "秒");
                    sendEmptyUIMessageDelay(MSG_UI_CHECK_SECOND, 1000);
                }
                mCurrentSecond--;
                break;
            case MSG_UI_ENTER_MAIN:
                startActivity(new Intent(this, MainActivity.class));
                finish();
                break;
        }
    }

    @Override
    public void showSplashView(SplashEntity splashEntity) {
        this.mSplashEntity = splashEntity;
        if (mSplashEntity != null && mSplashEntity.advEntities != null
                && mSplashEntity.advEntities.size() > 0) {
            Log.i(TAG, "showSplashView " + splashEntity.advEntities.size());
            mCurrentSecond = (int) Math.ceil(mSplashEntity.duration / 1000);
            mCurrentIndex = 0;
            if (mSplashEntity != null && mSplashEntity.advEntities != null
                    && mSplashEntity.advEntities.size() > 0) {
                if (mCurrentIndex < mSplashEntity.advEntities.size()) {
                    ADVEntity currentAdvEntity = mSplashEntity.advEntities.get(mCurrentIndex);
                    if (currentAdvEntity != null && !TextUtils.isEmpty(currentAdvEntity.img)) {
                        Log.i(TAG, "Glide:" + currentAdvEntity.img);
                        Glide.with(this).load(currentAdvEntity.img)
                                .placeholder(new ColorDrawable(Color.BLACK))
                                .into(new SimpleTarget<GlideDrawable>() {
                                    @Override
                                    public void onResourceReady(final GlideDrawable resource,
                                                                GlideAnimation<? super GlideDrawable> glideAnimation) {
                                        mIvSplash.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                mIvSplash.setImageDrawable(resource.getCurrent());
                                                stopLoading();
                                                sendEmptyUIMessage(MSG_UI_CHECK_SECOND);
                                                sendEmptyUIMessage(MSG_UI_REFRESH_ADV);
                                            }
                                        });
                                    }
                                });
                        return;
                    }
                }
            }

        }
        Log.i(TAG, "showSplashView showFailedView");
        showFailedView();
    }

    @Override
    public void showCurrentSplash(ADVEntity advEntity, int remainSeconds) {

    }

    @Override
    public void showFailedView() {
        sendEmptyUIMessage(MSG_UI_ENTER_MAIN);
    }
}
